package com.dqyt.app.service;


import com.alibaba.fastjson.JSON;
import com.dqyt.app.bean.Report;
import com.dqyt.app.bean.Sample;
import com.dqyt.app.bean.UserInfo;
import com.dqyt.app.bean.WorkBean;
import com.dqyt.app.mongo.ReportDao;
import com.dqyt.app.mongo.SampleDao;
import com.dqyt.common.check.CheckTool;
import com.dqyt.common.constant.AuthorityID;
import com.dqyt.common.constant.Opt;
import com.dqyt.common.utils.BHUtil;
import com.dqyt.common.utils.StringUtil;
import com.dqyt.common.utils.UserInfoUtil;
import com.dqyt.khjc.bean.*;
import com.dqyt.khjc.mapper.*;
import com.dqyt.khjc.mongo.WorkDao;
import com.dqyt.khjc.swicth.SwitchConfig;
import com.dqyt.khjc.utils.IpUtil;
import com.dqyt.khjc.utils.NumberUtil;
import com.dqyt.khjc.utils.TimeUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * 样品service
 */
@Service
public class AppWorkService {

    @Autowired
    private WorkMapper workMapper;

    @Autowired
    private HistoryMapper historyMapper;


    @Autowired
    private SampleDao sampleDao;

    @Autowired
    private ReportDao reportDao;

    /**
     * 分页查询 任务分配
     * @param request
     * @param page
     * @param size
     * @param rwdbh
     * @param mtype
     * @return
     */
    public ResultMsg getWorkListPage(HttpServletRequest request,Integer page,Integer size,long userId,
                                     String token,String rwdbh,long wtfId,int mtype,int workTYpe){
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {
            // 检查用户是否登录Token是否正确
            ret = UserInfoUtil.isAuthori_App(userId, token); // 验证用户是否登录
            // 如果有错误信息
            if (ret != null) {
                return ret;
            }
            ret = new ResultMsg(); // 声明一个返回值

            if (page != null && size != null) {
                page = (page - 1) * size;
            }

            int  workTYpeCh=0;
            int workTYpeCh2=0;

            if(workTYpe==88){
                workTYpe = 4;
                workTYpeCh = 1;
                workTYpeCh2=0;
            }else if(workTYpe==99){
                workTYpe = 4;
                workTYpeCh2=1;
                workTYpeCh=0;
            }
            List<WorkBean> workBeans =  workMapper.getAdWorkListPage( page, size, rwdbh, wtfId, mtype, workTYpe, workTYpeCh, workTYpeCh2);
            ret.setCode(ResultMsg.SUCESS);
            ret.setData(workBeans);
        }catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;
    }



    /**
     * 分页查询 任务分配
     * @param request
     * @param page
     * @param size
     * @param rwdbh
     * @param mtype
     * @return
     */
    public ResultMsg getWorkListPagex(HttpServletRequest request,Integer page,Integer size,long userId,
                                     String token,String rwdbh,long wtfId,int mtype,int workTYpe){
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {
            // 检查用户是否登录Token是否正确
            ret = UserInfoUtil.isAuthori_App(userId, token); // 验证用户是否登录
            // 如果有错误信息
            if (ret != null) {
                return ret;
            }
            ret = new ResultMsg(); // 声明一个返回值

            if (page != null && size != null) {
                page = (page - 1) * size;
            }

            int  workTYpeCh=0;
            int workTYpeCh2=0;

            if(workTYpe==88){
                workTYpe = 4;
                workTYpeCh = 1;
                workTYpeCh2=0;
            }else if(workTYpe==99){
                workTYpe = 4;
                workTYpeCh2=1;
                workTYpeCh=0;
            }
            List<WorkBean> workBeans =  workMapper.getAdWorkListPagex( page, size, rwdbh, wtfId, mtype, workTYpe, workTYpeCh, workTYpeCh2);
            ret.setCode(ResultMsg.SUCESS);
            ret.setData(workBeans);
        }catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;
    }



    /**
     * 分页查询 任务分配
     * @param request
     * @param page
     * @param size
     * @param rwdbh
     * @param mtype
     * @return
     */
    public ResultMsg getWorkListPage2(HttpServletRequest request,Integer page,Integer size,long userId,
                                     String token,String rwdbh,long wtfId,int mtype,int workTYpe){
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {
            // 检查用户是否登录Token是否正确
            ret = UserInfoUtil.isAuthori_App(userId, token); // 验证用户是否登录
            // 如果有错误信息
            if (ret != null) {
                return ret;
            }
            ret = new ResultMsg(); // 声明一个返回值

            if (page != null && size != null) {
                page = (page - 1) * size;
            }
            int  workTYpeCh=0;
            int workTYpeCh2=0;

            if(workTYpe==88){
                workTYpe = 4;
                workTYpeCh = 1;
                workTYpeCh2=0;
            }else if(workTYpe==99){
                workTYpe = 4;
                workTYpeCh2=1;
                workTYpeCh=0;
            }
            List<WorkBean> workBeans =  workMapper.getAdWorkListPage( page, size, rwdbh, wtfId, mtype, workTYpe, workTYpeCh, workTYpeCh2);
            ret.setCode(ResultMsg.SUCESS);
            ret.setData(workBeans);
        }catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;
    }




    /**
     * 快速分配任务
     *
     * @param request
     * @return
     */
    public ResultMsg setAssignTasks(HttpServletRequest request,String token,long userId,int type, long jcrId,String startNumberStr,String endNumberStr) {
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {
            // 检查用户是否登录Token是否正确
            ret = UserInfoUtil.isAuthori_App(userId, token); // 验证用户是否登录
            // 如果有错误信息
            if (ret != null) {
                return ret;
            }
            ret = new ResultMsg(); // 声明一个返回值
            // 权限检查
            // 首先取得用户信息
            User user = UserInfoUtil.getUserInfologin(userId, token);
            // 用户权限检查 是否可以管理待审核申请
            if (!CheckTool.checkAuthority(user, AuthorityID.ZYGL_KSFPRW)) {
                ret.setCode(ResultMsg.ERROR);
                ret.setMsg("你没有对应的操作权限");
                return ret;
            }
            //如果只有开始号
            if("".equals(endNumberStr)){
                int mybsbh =Integer.parseInt(startNumberStr);

                String mybsbhStr =String.valueOf(mybsbh);
                int mlength = startNumberStr.length() -mybsbhStr.length();
                String zhBsbh = NumberUtil.calculationBsbh(mybsbh,mlength,type);
                //增加
                WorkBean workBean =  new WorkBean();
                workBean.setBsbh(zhBsbh);
                workBean.setMtype(type);
                workBean.setAddTime(TimeUtil.currentTimeMillis());
                workBean.setAddUser(user.getUserId()+"");
                workMapper.addWork(workBean);
            }else{
                int startNumber = Integer.parseInt(startNumberStr);
                int endNumber = Integer.parseInt(endNumberStr);
                if(endNumber<=startNumber){
                    ret.setCode(ResultMsg.ERROR);
                    ret.setMsg("结束号必须大于开始号");
                    return ret;
                }
                int count = (endNumber - startNumber);
                for(int a =0;a<=count;a++){
                    int mybsbh =startNumber+a;
                    String mybsbhStr =String.valueOf(mybsbh);
                    int mlength = startNumberStr.length() -mybsbhStr.length();
                    String zhBsbh = NumberUtil.calculationBsbh(mybsbh,mlength,type);
                    //增加
                    WorkBean workBean =  new WorkBean();
                    workBean.setBsbh(zhBsbh);
                    workBean.setMtype(type);
                    workBean.setAddTime(TimeUtil.currentTimeMillis());
                    workBean.setAddUser(user.getUserId()+"");
                    workMapper.addWork(workBean);
                }
            }
            ret.setCode(ResultMsg.SUCESS);
            ret.setMsg("任务已生成");



            //如果操作日志的开关已经打开
            if(SwitchConfig.isOpen(SwitchConfig.ID_CZRZ)){
                //添维修记录
                String ip = IpUtil.getIpAddr(request);
                HistoryBean historyBean = new HistoryBean();
                historyBean.setMessage("[" + user.getUserName() + "]快速分配了任务：开始号为： [" + startNumberStr + "]结束号为：[" + endNumberStr + "]");
                historyBean.setType(Opt.RWYL_KSFPRW_RWFP);
                historyBean.setOpUserId(user.getUserId());
                historyBean.setIp(ip);
                historyBean.setBopId("");
                historyBean.setAddTime(TimeUtil.currentTimeMillis());
                historyBean.setAddUser(String.valueOf(user.getUserId()));
                historyBean.setUpdateTime(TimeUtil.currentTimeMillis());
                historyBean.setUpdateUser(String.valueOf(user.getUserId()));
                //插入数据库
                int ress = historyMapper.addHistory(historyBean);
            }

        } catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;
    }





    /**
     * 分配任务
     * @param request
     * @param bsbhArrar
     * @param jcrUserId
     * @param jcrStr
     * @return
     */
    public ResultMsg assignJobs(HttpServletRequest request,String token,long userId,String [] bsbhArrar,String jcrUserId,String jcrStr){
        List<Sample> sampleList = new ArrayList<Sample>();
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {
            // 检查用户是否登录Token是否正确
            ret = UserInfoUtil.isAuthori_App(userId, token); // 验证用户是否登录
            // 如果有错误信息
            if (ret != null) {
                return ret;
            }
            ret = new ResultMsg(); // 声明一个返回值

            if("".equals(jcrUserId) || bsbhArrar.length==0){
                ret.setCode(ResultMsg.ERROR);
                ret.setMsg("非法操作");
                return ret;
            }
            int res = workMapper.updateStateByIDs(bsbhArrar,Long.parseLong(jcrUserId),jcrStr,2);
            if(res>0){
                ret.setCode(ResultMsg.SUCESS);
                ret.setMsg("操作成功");
                return ret;
            }else{
                ret.setCode(ResultMsg.ERROR);
                ret.setMsg("未知的错误，请稍候再试！");
                return ret;
            }

        }catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;
    }




    /**
     * 分页查询 任务
     * @param request
     * @param page
     * @param size
     * @param rwdbh
     * @param wtfId
     * @param mtype
     * @return
     */
    public ResultMsg getWorkListPage5(HttpServletRequest request,String token,long userId,Integer page,Integer size,String rwdbh,
                                     long wtfId,int mtype,int workTYpe,int workTYpeCh,int workTYpeCh2,long jyyId){
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {
            // 检查用户是否登录Token是否正确
            ret = UserInfoUtil.isAuthori_App(userId, token); // 验证用户是否登录
            // 如果有错误信息
            if (ret != null) {
                return ret;
            }
            ret = new ResultMsg(); // 声明一个返回值


            if (page != null && size != null) {
                page = (page - 1) * size;
            }
            List<WorkBean> workBeans =  workMapper.getWorkListPage(page,size,rwdbh,wtfId,mtype,workTYpe,workTYpeCh,workTYpeCh2,jyyId);
            ret.setCode(ResultMsg.SUCESS);
            ret.setData(workBeans);
        }catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;
    }


    /**
     * 设置任务状态
     * @param request
     * @param token
     * @param userId
     * @param bsbhArrar
     * @param workTYpe
     * @return
     */
    public ResultMsg setworkTYpeYdy(HttpServletRequest request,String token,long userId,String [] bsbhArrar,int  workTYpe){
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {
            // 检查用户是否登录Token是否正确
            ret = UserInfoUtil.isAuthori_App(userId, token); // 验证用户是否登录
            // 如果有错误信息
            if (ret != null) {
                return ret;
            }
            ret = new ResultMsg(); // 声明一个返回值

            //将数组转为list
            List<String> listB= new ArrayList<>();
            for(int c=0;c<bsbhArrar.length;c++){
                listB.add(bsbhArrar[c]);
            }

            //创建新列表 用来装充气的但是没有报告的气瓶
            List<String> qpzhuan4 = new ArrayList<>();
            //批量查询是充气的气瓶
            List<Sample> qclist =  sampleDao.getReportByBatchCq(listB);
            for(Sample sample:qclist){
                //查询报告
                Report report =   reportDao.getReportBybsbh(sample.bsbh,2);
                if(null == report){
                    qpzhuan4.add(sample.bsbh);
                }
            }

            //将是充气的 但是没有报告的直接转到 待装箱 但是已完成
            int res = workMapper.setworkTYpeYzxTo4(bsbhArrar);
            for(int i = listB.size() - 1; i >= 0; i--){
                String item = listB.get(i);
                if(qpzhuan4.contains(item)){
                    listB.remove(item);
                }
            }
            if(listB.size()>0){
                String[] mbsbhArr = new String[listB.size()];
                listB.toArray(mbsbhArr);
                int res3 = workMapper.setworkTYpeYdy(mbsbhArr,workTYpe);
                if(res3>0){
                    ret.setCode(ResultMsg.SUCESS);
                    ret.setMsg("操作成功");
                    return ret;
                }else{
                    ret.setCode(ResultMsg.ERROR);
                    ret.setMsg("未知的错误，请稍候再试！");
                    return ret;
                }
            }else{
                ret.setCode(ResultMsg.SUCESS);
                ret.setMsg("操作成功");
                return ret;
            }

        }catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;
    }



    /**
     * 设置任务状态 已完成
     * @param request
     * @param bsbhArrar
     * @return
     */
    public ResultMsg setworkTYpeYwc(HttpServletRequest request,String token,long userId,String [] bsbhArrar){
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {
            // 检查用户是否登录Token是否正确
            ret = UserInfoUtil.isAuthori_App(userId, token); // 验证用户是否登录
            // 如果有错误信息
            if (ret != null) {
                return ret;
            }
            ret = new ResultMsg(); // 声明一个返回值
            // 权限检查
            //更新已完成并且是已装箱的
            long res =  workMapper.updateWcOrYzxList(bsbhArrar);
            //更新已完成单是未装箱的
            long res2 = workMapper.updateYwcOrWzxList(bsbhArrar);
            if(res>0 || res2>0 ){
                ret.setCode(ResultMsg.SUCESS);
                ret.setMsg("操作成功");
                return ret;
            }else{
                ret.setCode(ResultMsg.ERROR);
                ret.setMsg("未知的错误，请稍候再试！");
                return ret;
            }
        }catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;
    }



    /**
     * 设置任务状态 已装箱
     * @param request
     * @param bsbhArrar
     * @return
     */
    public ResultMsg setworkTYpeYzx(HttpServletRequest request,String token,long userId,String [] bsbhArrar){
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {
            // 检查用户是否登录Token是否正确
            ret = UserInfoUtil.isAuthori_App(userId, token); // 验证用户是否登录
            // 如果有错误信息
            if (ret != null) {
                return ret;
            }
            ret = new ResultMsg(); // 声明一个返回值
            //更新已装箱 并且是已完成的
            long res =  workMapper.updateYzxOrYwcList(bsbhArrar);
            long res2 = workMapper.updateYzxOrWwcList(bsbhArrar);
            if(res>0 || res2>0 ){
                ret.setCode(ResultMsg.SUCESS);
                ret.setMsg("操作成功");
                return ret;
            }else{
                ret.setCode(ResultMsg.ERROR);
                ret.setMsg("未知的错误，请稍候再试！");
                return ret;
            }
        }catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;
    }




    /**
     * 设置任务状态 已发放
     * @param request
     * @param bsbhArrar
     * @return
     */
    public ResultMsg setworkTYpeYff(HttpServletRequest request,String token,long userId,String [] bsbhArrar){
        ResultMsg ret = new ResultMsg(); // 声明一个返回值
        try {
            // 检查用户是否登录Token是否正确
            ret = UserInfoUtil.isAuthori_App(userId, token); // 验证用户是否登录
            // 如果有错误信息
            if (ret != null) {
                return ret;
            }
            ret = new ResultMsg(); // 声明一个返回值
            //更新已装箱 并且是已完成的
            long res =  workMapper.setworkTYpeYff(bsbhArrar);
            if(res>0 ){
                ret.setCode(ResultMsg.SUCESS);
                ret.setMsg("操作成功");
                return ret;
            }else{
                ret.setCode(ResultMsg.ERROR);
                ret.setMsg("未知的错误，请稍候再试！");
                return ret;
            }
        }catch (Exception e) {
            ret.setCode(ResultMsg.ERROR);
            ret.setMsg("未知的错误，请稍候再试！");
            e.printStackTrace();
        }
        return ret;
    }


}
